package com.app.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

public class WechatUtil {
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Resource
    private static RestTemplate restTemplate = SpringUtils.getBean(RestTemplate.class);

    //获取手机号
    public static String getMobile(String mobileCode) {
        // 获取token
        String token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", WXConstant.APPID, WXConstant.SECRET);
        JSONObject token = JSON.parseObject(HttpUtil.get(token_url));
        // 使用前端code获取手机号码 参数为json格式
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token.getString("access_token");
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("code", mobileCode);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
        System.out.println(httpEntity);
        ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);
        Object body = response.getBody();
        Map<String, Object> map = new ObjectMapper().convertValue(body, Map.class);
        Object phoneInfo = map.get("phone_info");
        Map<String, Object> map1 = new ObjectMapper().convertValue(phoneInfo, Map.class);
        // 以上都是response参数的处理 最终拿到userPhone 可以进行下一步 微信登陆了
        Object phoneNumber = map1.get("phoneNumber");
        return (String) phoneNumber;
    }

    //获取Openid
    public static String getOpenid(String code) {
        //请求封装参数
        Map<String, String> map = new HashMap<>();
        map.put("appid", WXConstant.APPID);
        map.put("secret", WXConstant.SECRET);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        return jsonObject.getString("openid");
    }
}
